package service

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"sgo/app/system/dto"
	"sgo/app/system/model"
	"sgo/common/utils"
	"sgo/rewrite"
	"sgo/scontext"
)

type UserService struct{}

func (UserService) Create(ctx *gin.Context, sc *scontext.SgoContext, userDTO *dto.UserDTO) {

	user := new(model.User)

	err := utils.StructUtils.StructCopy(userDTO, user)

	if err != nil {
		panic(err)
	}

	user.CreateTime = rewrite.Now()
	user.UpdateTime = rewrite.Now()
	sc.DB.Create(user)
}

// 查询全部用户列表

func (s UserService) List(ctx *gin.Context, sc *scontext.SgoContext) []model.User {

	userList := make([]model.User, 1)

	sc.DB.Find(&userList)

	return userList
}

// 根据ID删除

func (s UserService) Delete(ctx *gin.Context, sc *scontext.SgoContext, id int) {
	tx := sc.DB.Delete(&model.User{ID: id})
	if tx.Error != nil {
		panic(tx.Error)
	}
}

func (s UserService) Update(ctx *gin.Context, sc *scontext.SgoContext, userDTO *dto.UserDTO) {

	user := new(model.User)

	err := utils.StructUtils.StructCopy(userDTO, user)

	if err != nil {
		panic(err)
	}

	user.UpdateTime = rewrite.Now()
	sc.DB.Updates(user)

}

// 测试事务回滚

func (s UserService) CreateAndDelete(ctx *gin.Context, sc *scontext.SgoContext, userDTO *dto.UserDTO) {

	err := sc.DB.Transaction(func(tx *gorm.DB) error {

		user := new(model.User)

		err := utils.StructUtils.StructCopy(userDTO, user)

		if err != nil {
			panic(err)
		}

		user.CreateTime = rewrite.Now()
		user.UpdateTime = rewrite.Now()
		tx.Create(user)

		tx.Delete(&model.User{ID: 6})

		return errors.New("事务回滚")
	})

	if err != nil {
		panic(err)
	}

}
